<?php
namespace app\api\controller\basemanage;
use app\api\controller\common\ApiBase;
use think\Controller; // den
use think\Db;
use app\api\model\Admin as AdminModel;
use app\api\controller\common\AuthorCon;
// Controller  ApiBase （dengl）
class Order extends ApiBase
{
    /**
     *
     * @return \think\response\Json|void
     *  comppub
     *
     */

    public function getList(){
        $admin = session('admin');
        $admin = AdminModel::get(['id' => $admin['id']]);
        $page = $this->request->param('pageIndex');
        $mobile = $this->request->param('mobile');
        $name = $this->request->param('name');
        $store_id = $this->request->param('store_id');
        if($admin['is_super']!=0){$store_id=$admin['org_id'];};
        $status = $this->request->param('status');
        $technician_id = $this->request->param('technician_id');
        $page = max(1,intval($page));
        $pageSize =$this->request->param('pageSize')==""?20:$this->request->param('pageSize');
        $param=" and o.is_delete=0";
        if (!empty($mobile)) {
            $param.=" and o.member_id in (select id from crm_member_user where mobile like '%$mobile%' and is_delete=0) ";
        }
        if (!empty($name)) {
            $param.=" and o.member_id in (select id from crm_member_user where nickname like '%$name%' and is_delete=0) ";
        }
        if (!empty($store_id)) {
            $param.=" and o.store_id=".$store_id;
        }
        if (!empty($store_id)) {
            $param.=" and o.technician_id=".$technician_id;
        }
        if (!empty($status)) {
            $param.=" and o.status=".$status;
        }
        $sql2="SELECT o.*,s.title as store_title,c.name as server_name,c.price as server_price,t.name as technician_name,q.monetary,q.record_type,q.katz_or_amount,u.nickname,u.mobile,u.wash_protect_num_total,u.wechat_nickname FROM crm_user_order AS o ";
        $sql2.=" LEFT JOIN crm_store AS s ON s.id=o.store_id ";
        $sql2.=" LEFT JOIN crm_server_subscribe AS c ON c.id=o.server_id ";
        $sql2.=" LEFT JOIN crm_technician AS t ON t.id=o.technician_id ";
        $sql2.=" LEFT JOIN crm_member_record AS q ON q.order_id=o.id ";
        $sql2.=" LEFT JOIN crm_member_user AS u ON u.id=o.member_id ";
        $sql2.=" where 1=1 $param";
        $sql2.=" order by o.create_time desc";
        $total1=Db::query($sql2);
        $sql2.=" limit ".($page-1)*$pageSize.",$pageSize";
        $list=Db::query($sql2);
        $total=count($total1); //st
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'total'=>$total]]);
    }


    /**
     * 添加
     * @return \think\response\Json|void
     *  zs_question       zs_question_option
     *  zs_question_type
     */
    public function add(){
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $member_id=isset($post['member_id']) && $post['member_id'] != '' ? $post['member_id'] : 0;
                $rUser=db('member_user')->where(['is_delete'=>0,'id'=>$member_id])->find();
                if(!$rUser){
                    return json(array('code' => '0', 'msg' => '人员信息错误'));
                }
                $order_id=isset($post['order_id']) && $post['order_id'] != '' ? $post['order_id'] : 0;
                $oRes=db('user_order')->where(['id'=>$order_id])->find();
                if(!$oRes){
                    return json(['code' => 0, 'msg' => '订单信息错误']);
                }
                $server_id=isset($post['server_id']) && $post['server_id'] != '' ? $post['server_id'] : 0;
                $sRes=db('server')->where(['id'=>$server_id])->find();
                if(!$sRes){
                    return json(['code' => 0, 'msg' => '服务信息错误']);
                }

                $checked=isset($post['checked']) && $post['checked'] != '' ? $post['checked'] : 0;
                $washchecked=isset($post['washchecked']) && $post['washchecked'] != '' ? $post['washchecked'] : 0;
                $amountChecked=isset($post['amountChecked']) && $post['amountChecked'] != '' ? $post['amountChecked'] : 0;

                if($checked!=1 && $washchecked!=1 && $amountChecked != 1){
                    return json(array('code' => '0', 'msg' => '金额未填写'));
                }
                $data['record_type']=0;
                $data['katz_or_amount']=0;
                //是否使用积分

                $integralNum=isset($post['integralNum']) && $post['integralNum'] != '' ? $post['integralNum'] : 0;
                if($integralNum>0 && $checked==1){
                    if($integralNum<1000){
                        return json(array('code' => '0', 'msg' => '请选择积分'));
                    }
                    $integralDate['update_time']=time();
                    $integralDate['create_time']=time();
                    $integralDate['recharge_type']=1;
                    $integralDate['integral_type']=2;
                    $integralDate['member_id']=$member_id;
                    $integralDate['integral_num']=$integralNum;
                    $integralRes=db('member_integral')->lock(true)->insert($integralDate);
                    if(false === $integralRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                }
                //是否使用卡次
                $washProtectNum=isset($post['washProtectNum']) && $post['washProtectNum'] != '' ? $post['washProtectNum'] : 0;
                if($washchecked==1){
                    if($washProtectNum<1){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '请选择一次卡次'));
                    }
                    if($rUser['wash_protect_num_total'] <$washProtectNum){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '卡次余额不足'));
                    }
                    $wash_protect_num_total=$rUser['wash_protect_num_total']-$washProtectNum;
                    $userR=db('member_user')->where(['is_delete'=>0,'id'=>$member_id])->update(['wash_protect_num_total'=>$wash_protect_num_total]);
                    if(false === $userR){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                    $data['record_type']=1;
                    $data['katz_or_amount']=1;
                }

                //是否使用余额
                $actualAmount=isset($post['actualAmount']) && $post['actualAmount'] != '' ? $post['actualAmount'] : 0;
                if($amountChecked == 1){
                    if($actualAmount==0){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '金额未填写'));
                    }
                    $amountNum=db('member_recharge')->where(['is_delete'=>0,'member_id'=>$member_id])->sum('amount');
                    $xfAmountNum=db('member_record')->where(['is_delete'=>0,'member_id'=>$member_id,'katz_or_amount'=>2])->sum('monetary');
                    if($actualAmount>($amountNum-$xfAmountNum)){
                        Db::rollback();
                        return json(['code' => 0, 'msg' => '账户额度不够']);
                    }
                    $data['record_type']=2;
                    $data['katz_or_amount']=2;
                }

                if($actualAmount>0){
                    $integralDateI['update_time']=time();
                    $integralDateI['create_time']=time();
                    $integralDateI['recharge_type']=1;
                    $integralDateI['integral_type']=1;
                    $integralDateI['member_id']=$member_id;
                    $integralDateI['integral_num']=$actualAmount;
                    $integralRes=db('member_integral')->lock(true)->insert($integralDateI);
                    if(false === $integralRes){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败'));
                    }
                }
                $data['member_id']=$member_id;
                $data['order_id']=$order_id;
                $data['server_id']=$server_id;
                $data['create_time']=time();
                $data['update_time']=time();
                $data['monetary']=$actualAmount;
                $record=db('member_record')->lock(true)->insert($data);
                if(false === $record){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败,添加失败'));
                }
                $orderData['play_time']=time();
                $orderData['status']=5;
                $orderData['order_price']=$actualAmount;
                $oRes=db('user_order')->where(['id'=>$order_id])->update($orderData);
                if(false === $oRes){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败,添加失败'));
                }
                Db::commit();
                return json(array('code' => '1', 'msg' => '成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 删除
     */
    public function del(){
        $id = $this->request->param('id');
        if(empty($id)){
            return json(['code'=>0,'msg'=>'参数有误','data'=>'']);
        }
        $r=db('member_vip')->where(['is_delete'=>0,'id'=>$id])->find();
        if(!$r){
            return json(['code'=>0,'msg'=>'会员信息查询失败']);
        }
        $res=db('member_vip')->where(['id'=>$id])->update(['is_delete'=>0]);
        if(!$res){
            return json(['code'=>0,'msg'=>'操作失败']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);

    }


    /**
     * 获取门店技师
     * @return \think\response\Json|void
     */
    public function technicianList()
    {
        $post = input('post.');
        $store_id = isset($post['store_id']) && $post['store_id'] != '' ? $post['store_id'] : 0;
        $sRes=db('store')->where(['id'=>$store_id,'is_delete'=>0,'status'=>0])->find();
        if(!$sRes){
            return json(['code' => 0, 'msg' => '门店信息错误']);
        }
        $where['is_delete'] = 0;
        $where['status'] = 0;
        $where['is_technician'] = 1;
        $where['store_id'] = $store_id;
        $r=db('technician')->where($where)->select();
        return json(['code' => 1, 'msg' => '操作成功','data'=>$r]);
    }

    /**
     * 订单入库
     * @return \think\response\Json|void
     */
    public function technicianAdd()
    {
        $post = input('post.');
        $order_id = isset($post['order_id']) && $post['order_id'] != '' ? $post['order_id'] : 0;
        $oRes=db('user_order')->where(['id'=>$order_id])->find();
        if(!$oRes){
            return json(['code' => 0, 'msg' => '订单信息错误']);
        }
        if($oRes['status']>2){
            return json(['code' => 0, 'msg' => '订单状态错误']);
        }
        $chnician_id = isset($post['chnician_id']) && $post['chnician_id'] != '' ? $post['chnician_id'] : 0;
        $tRes=db('technician')->where(['id'=>$chnician_id])->find();
        if(!$tRes){
            return json(['code' => 0, 'msg' => '技师信息错误']);
        }
        $data['technician_id']=$chnician_id;
        $data['update_time']=time();
        $data['status']=2;
        $r=db('user_order')->where(['id'=>$order_id])->update($data);
        if(!$r){
            return json(['code' => 0, 'msg' => '操作失败']);
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }

    /**
     * 获取充值卡列表
     * @return \think\response\Json|void
     */
    public function userDetail()
    {
        $post = input('post.');
        $member_id = isset($post['member_id']) && $post['member_id'] != '' ? $post['member_id'] : 0;
        $oRes=db('member_user')->where(['id'=>$member_id,'is_delete'=>0])->find();
        if(!$oRes){
            return json(['code' => 0, 'msg' => '用户信息错误']);
        }
        $serve_id = isset($post['server_id']) && $post['server_id'] != '' ? $post['server_id'] : 0;
        $sRes=db('server')->where(['id'=>$serve_id,'is_delete'=>0,'status'=>0])->find();
        if(!$sRes){
            return json(['code' => 0, 'msg' => '服务信息错误']);
        }
        $vipRes=db('member_vip')->where(['is_delete'=>0,'member_id'=>$member_id,'card_end_time'=>array('egt',time())])->find();
        $amount=db('member_recharge')->where(['is_delete'=>0,'member_id'=>$member_id])->sum('amount');
        //开始消费数据
        $amountNum=db('member_record')->where(['is_delete'=>0,'member_id'=>$member_id,'record_type'=>2,'katz_or_amount'=>2])->sum('monetary');
        $integral_sr=db('member_integral')->where(['member_id'=>$member_id,'integral_type'=>1])->sum('integral_num');
        $integral_xf=db('member_integral')->where(['member_id'=>$member_id,'integral_type'=>2])->sum('integral_num');
        return json(['code' => 1, 'msg' => '操作成功','vipRes'=>$vipRes,'userDetail'=>$oRes,'amount'=>$amount-$amountNum,'integral'=>($integral_sr-$integral_xf)]);
    }

    /**
     * 获取会员详情
     * @return \think\response\Json|void
     */
    public function changeStatus()
    {
        $post = input('post.');
        $order_id = isset($post['order_id']) && $post['order_id'] != '' ? $post['order_id'] : 0;
        $status = isset($post['status']) && $post['status'] != '' ? $post['status'] : 0;
        $oRes=db('user_order')->where(['id'=>$order_id])->find();
        if(!$oRes){
            return json(['code' => 0, 'msg' => '订单信息错误']);
        }
        $where['id'] = $order_id;
        $data['status'] = $status;
        $data['update_time'] = time();
        $r=db('user_order')->where($where)->update($data);
        if(!$r){
            return json(['code' => 0, 'msg' => '操作失败']);
        }
        return json(['code' => 1, 'msg' => '操作成功']);
    }

    /**
     *    // 提货通知
     * https://xcx.gwsp.vip/api/basemanage/Order/deliveryNotice
     *
     *
     */


    public function deliveryNotice(){
        $auth= new AuthorCon();

        $post = input('post.');
        $order_id = isset($post['order_id']) && $post['order_id'] != '' ? $post['order_id'] : 0;
        $oRes=db('user_order')->where(['id'=>$order_id])->find();
        if(!$oRes){
            return json(['code' => 0, 'msg' => '订单信息错误']);
        }
        $param=" and o.id=".$order_id;
        $sql2="SELECT o.*,s.title as store_title,s.address as store_address,s.lat as store_lat,s.lng as store_lng,s.tel as store_tel,c.name as server_name,c.price as server_price,t.name as technician_name,q.monetary,q.record_type,q.katz_or_amount,u.nickname,u.mobile FROM crm_user_order AS o ";
        $sql2.=" LEFT JOIN crm_store AS s ON s.id=o.store_id ";
        $sql2.=" LEFT JOIN crm_server_subscribe AS c ON c.id=o.server_id ";
        $sql2.=" LEFT JOIN crm_technician AS t ON t.id=o.technician_id ";
        $sql2.=" LEFT JOIN crm_member_record AS q ON q.order_id=o.id ";
        $sql2.=" LEFT JOIN crm_member_user AS u ON u.id=o.member_id ";
        $sql2.=" where 1=1 $param";
        $list=Db::query($sql2);
        if(is_array($list) && count($list)>0){
            $odinfo=$list[0];
            // store_title 门店名称 order_num 订单号 subscribe_time 预约时间--是时间戳 server_name 预约类型
            //
            $odinfo['subscribe_time']=date('Y-m-d', $odinfo['subscribe_time']);

            $para=array("store_title"=>$odinfo['store_title'],"order_num"=>$odinfo['order_num'],"subscribe_time"=>$odinfo['subscribe_time'],
                        "server_name"=>$odinfo['server_name']);
            $res=$auth->sendOrdertihuo($oRes['openid'],$para);

            // errmsg
//            return $res;
            if($res['errcode']>0){
                //return $res;
                return json(['code' => 0, 'msg' =>$res['errmsg']."code:".$res['errcode']]);
            }else{
                return json(['code' => 1, 'msg' => '操作成功']);
            }
           // var_dump($res);die;



        }
        return json(['code' => 0, 'msg' => '订单信息错误']);
    }

    /**
     * 获取充值卡充值记录
     * @return \think\response\Json|void
     */
    public function getStoredDetail()
    {
        $post = input('post.');
        $member_id = isset($post['member_id']) && $post['member_id'] != '' ? $post['member_id'] : 0;
        $user=db('member_user')->where(['is_delete'=>0,'id'=>$member_id])->find();
        if(!$user){
            return json(['code' => 0, 'msg' => '会员信息错误']);
        }
        $where['is_delete'] = 0;
        $where['member_id'] = $member_id;
        $r=db('member_recharge')->where($where)->select();
        return json(['code' => 1, 'msg' => '操作成功','data'=>$r]);
    }


    /**
     * 获取服务卡记录
     * @return \think\response\Json|void
     */
    public function getServerDetail()
    {
        $post = input('post.');
        $member_id = isset($post['member_id']) && $post['member_id'] != '' ? $post['member_id'] : 0;
        $user=db('member_user')->where(['is_delete'=>0,'id'=>$member_id])->find();
        if(!$user){
            return json(['code' => 0, 'msg' => '会员信息错误']);
        }
        $sql="select sd.*,a.server_total,s.title as server_title,s.server_num,s.card_price from crm_member_serve AS sd ";
        $sql.=" left join crm_cards_server as s on s.id=sd.serve_id ";
        $sql.=" LEFT JOIN (SELECT COUNT(id) as server_total,server_card_id FROM crm_member_record WHERE is_delete=0 GROUP BY server_card_id) AS a ON a.server_card_id=sd.id ";
        $sql.=" where 1=1 and sd.is_delete=0 and sd.member_id=".$member_id;
        $sql.=" order by sd.id desc ";
        $list=Db::query($sql);
        foreach ($list as &$v){
            $v['server_status']=$v['card_end_time']>=time()?1:0;
        }
        return json(['code' => 1, 'msg' => '操作成功','data'=>$list]);
    }


    /**
     * 获取充值卡充值记录
     * @return \think\response\Json|void
     */
    public function purchaseHistory()
    {
        $post = input('post.');
        $member_id = isset($post['member_id']) && $post['member_id'] != '' ? $post['member_id'] : 0;
        $user=db('member_user')->where(['is_delete'=>0,'id'=>$member_id])->find();
        if(!$user){
            return json(['code' => 0, 'msg' => '会员信息错误']);
        }
        $where['xf.is_delete'] = 0;
        $where['xf.member_id'] = $member_id;
        $list = Db::name('member_record')
            ->alias('xf')
            ->field('xf.*,s.name as server_name')
            ->join('server s','s.id=xf.server_id','left')
            ->where($where)
            ->order('xf.id desc')
            ->select();
        return json(['code' => 1, 'msg' => '操作成功','data'=>$list]);
    }

    public function addOrderList(){
        $server_list=db('server_cate_subscribe')->where(['is_delete'=>0])->order('sort desc')->select();
        foreach ($server_list as &$v){
            $v['name']=$v['title'];
            $v['child'] = db('server_subscribe')->where(['cate_id'=>$v['id'],'is_delete'=>0,'status'=>0])->select();
        }
        $store_list=db('store')->where(['is_delete'=>0])->order('sort desc')->select();
        foreach ($store_list as &$vv){
            $vv['technician_list'] = db('technician')->where(['store_id'=>$vv['id'],'is_delete'=>0,'is_technician'=>1])->select();
        }
        return json(['code' => 1, 'msg' => '操作成功','server_list'=>$server_list,'store_list'=>$store_list]);
    }

    public function addOrders(){
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $mobile = isset($post['mobile']) && $post['mobile'] != '' ? $post['mobile'] : null;
                $nickname = isset($post['nickname']) && $post['nickname'] != '' ? $post['nickname'] : null;
                $store_id = isset($post['store_id']) && $post['store_id'] != '' ? $post['store_id'] : 0;
                $technician_id = isset($post['technician_id']) && $post['technician_id'] != '' ? $post['technician_id'] : 0;
                $server_id = isset($post['server_id']) && $post['server_id'] != '' ? $post['server_id'] : 0;
                if(!$mobile && !$nickname){
                    return json(['code' => 0, 'msg' => '会员信息错误']);
                }
                $store=db('store')->where(['is_delete'=>0,'id'=>$store_id])->find();
                if(!$store){
                    return json(['code' => 0, 'msg' => '店铺信息错误']);
                }
                $technician=db('technician')->where(['is_delete'=>0,'id'=>$technician_id,'is_technician'=>1])->find();
                if(!$technician){
                    return json(['code' => 0, 'msg' => '技师信息错误']);
                }
                $server=db('server_subscribe')->where(['is_delete'=>0,'id'=>$server_id])->find();
                if(!$server){
                    return json(['code' => 0, 'msg' => '服务信息错误']);
                }
                $rUser=db('member_user')->where(['is_delete'=>0,'mobile'=>$mobile])->find();
                $remember_id=null;
                if(!$rUser){
                    $userDate['update_time']=time();
                    $userDate['create_time']=time();
                    $userDate['nickname']=$nickname;
                    $userDate['mobile']=$mobile;
                    $remember_id=db('member_user')->lock(true)->insertGetId($userDate);
                    if(false === $remember_id){
                        Db::rollback();
                        return json(array('code' => '0', 'msg' => '操作失败,会员信息添加失败'));
                    }
                }else{
                    $remember_id=$rUser['id'];
                }
                $data['order_num']=date('YmdHis').rand(1000,9999);
                $data['create_time']=time();
                $data['update_time']=time();
                $data['member_id']=$remember_id;
                $data['subscribe_time']=time();
                $data['store_id']=$store_id;
                $data['server_id']=$server_id;
                $data['technician_id']=$technician_id;
                $data['status']=2;
                $r=db('user_order')->insert($data);
                if(false === $r){
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => '操作失败'));
                }
                Db::commit();
                return json(array('code' => '1', 'msg' => '成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    public function hxImgList(){
        $post = input('post.');
        $order_id = isset($post['order_id']) && $post['order_id'] != '' ? $post['order_id'] : 0;
        $oRes=db('user_order')->where(['id'=>$order_id])->find();
        if(!$oRes){
            return json(['code' => 0, 'msg' => '订单信息错误']);
        }
        $r=db('user_order_img')->where(['order_id'=>$order_id])->select();
        return json(['code' => 1, 'msg' => 'ok','data'=>$r]);
    }
}